<!DOCTYPE html>

<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <title>Potion Section Movement / Learn Vimscript the Hard Way</title>
        <meta name="description" content="">
        <meta name="author" content="Steve Losh">
        <!--[if lt IE 9]>
            <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->

        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

        <link href="/static/styles/skeleton/base.css" rel="stylesheet" type="text/css" />
        <link href="/static/styles/skeleton/skeleton.css" rel="stylesheet" type="text/css" />
        <link href="/static/styles/skeleton/layout.css" rel="stylesheet" type="text/css" />

        <link href="/static/styles/tango.css" rel="stylesheet" type="text/css" />
        <link href="/static/styles/style.less" rel="stylesheet/less" type="text/css" />

        <script type="text/javascript" src="/static/scripts/less.js"></script>
    </head>

    <body class="">
        <div class="container">
            <header class="sixteen columns">
                <h1><a href="/">Learn Vimscript the Hard Way</a></h1>
            </header>

            
    <section class="nav three columns">
        
<ul>
<li><a href="#potion-section-movement">Potion Section Movement</a><ul>
<li><a href="#custom-mappings">Custom Mappings</a></li>
<li><a href="#using-a-function">Using a Function</a></li>
<li><a href="#base-movement">Base Movement</a></li>
<li><a href="#top-level-text-sections">Top Level Text Sections</a></li>
<li><a href="#search-flags">Search Flags</a></li>
<li><a href="#function-definitions">Function Definitions</a></li>
<li><a href="#visual-mode">Visual Mode</a></li>
<li><a href="#why-bother">Why Bother?</a></li>
<li><a href="#exercises">Exercises</a></li>
</ul>
</li>
</ul>


        <div class="prevnext">
            
                <a class="prev" href="50.html">&laquo; Prev</a>
            
            
                <a class="next" href="52.html">Next &raquo;</a>
            
        </div>
    </section>

    <section class="content twelve columns offset-by-one">
        <div> 
<h1 id="potion-section-movement">Potion Section Movement</h1>
<p>Now that we know how section movement works, let's remap the commands to work
in a way that makes sense for Potion files.</p>
<p>First we need to decide what "section" should mean for a Potion file.  There are
two pairs of section movement commands, so we can come up with two "schemes" and
our users can use the one they prefer.</p>
<p>Let's use the following two schemes to define where Potion sections start:</p>
<ol>
<li>Any line following a blank line that contains non-whitespace as the first
   character, or the first line in the file.</li>
<li>Any line that contains non-whitespace as the first character, an equal sign
   somewhere inside the line, and ends with a colon.</li>
</ol>
<p>Using a slightly-expanded version of our sample <code>factorial.pn</code> file, here's
what these rules will consider to be section headers:</p>
<pre class="codehilite"><code class="language-text"># factorial.pn                              1
# Print some factorials, just for fun.

factorial = (n):                            1 2
    total = 1

    n to 1 (i):
        total *= i.

    total.

print_line = ():                            1 2
    "-=-=-=-=-=-=-=-\n" print.

print_factorial = (i):                      1 2
    i string print
    '! is: ' print
    factorial (i) string print
    "\n" print.

"Here are some factorials:\n\n" print       1

print_line ()                               1
10 times (i):
    print_factorial (i).
print_line ()</code></pre>


<p>Our first definition tends to be more liberal.  It defines a section to be
roughly a "top-level chunk of text".</p>
<p>The second definition is more restrictive.  It defines a section to be
(effectively) a function definition.</p>
<h2 id="custom-mappings">Custom Mappings</h2>
<p>Create a <code>ftplugin/potion/sections.vim</code> file in your plugin's repo.  This
is where we'll put the code for section movement.  Remember that this code will
be run whenever a buffer's <code>filetype</code> is set to <code>potion</code>.</p>
<p>We're going to remap all four section movement commands, so go ahead and create
a "skeleton" file:</p>
<pre class="codehilite"><code class="language-vim">noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; [[ &lt;nop&gt;
noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; ]] &lt;nop&gt;

noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; [] &lt;nop&gt;
noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; ][ &lt;nop&gt;</code></pre>


<p>Notice that we use <code>noremap</code> commands instead of <code>nnoremap</code>, because we want
these to work in operator-pending mode too.  That way you'll be able to do
things like <code>d]]</code> to "delete from here to the next section".</p>
<p>We make the mappings buffer-local so they'll only apply to Potion files and
won't take over globally.</p>
<p>We also make them silent, because the user won't care about the details of how
we move between sections.</p>
<h2 id="using-a-function">Using a Function</h2>
<p>The code for performing the section movements is going to be very similar for
all of the various commands, so let's abstract it into a function that our
mappings will call.</p>
<p>You'll see this strategy in a lot of Vim plugins that create a number of similar
mappings.  It's easier to read and maintain than stuffing all the functionality
in to a bunch of mapping lines.</p>
<p>Change the <code>sections.vim</code> file to contain this:</p>
<pre class="codehilite"><code class="language-vim">function! s:NextSection(type, backwards)
endfunction

noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; ]]
        \ :call &lt;SID&gt;NextSection(1, 0)&lt;cr&gt;

noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; [[
        \ :call &lt;SID&gt;NextSection(1, 1)&lt;cr&gt;

noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; ][
        \ :call &lt;SID&gt;NextSection(2, 0)&lt;cr&gt;

noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; []
        \ :call &lt;SID&gt;NextSection(2, 1)&lt;cr&gt;</code></pre>


<p>I used Vimscript's long line continuation feature here because the lines were
getting a bit long for my taste.  Notice how the backslash to escape long lines
comes at the <em>beginning</em> of the second line.  Read <code>:help line-continuation</code> for
more information.</p>
<p>Notice that we're using <code>&lt;SID&gt;</code> and a script-local function to avoid polluting
the global namespace with our helper function.</p>
<p>Each mapping simply calls <code>NextSection</code> with the appropriate arguments to
perform the movement.  Now we can start implementing <code>NextSection</code>.</p>
<h2 id="base-movement">Base Movement</h2>
<p>Let's think about what our function needs to do.  We want to move the cursor to
the next "section", and an easy way to move the cursor somewhere is with the <code>/</code>
and <code>?</code> commands.</p>
<p>Edit <code>NextSection</code> to look like this:</p>
<pre class="codehilite"><code class="language-vim">function! s:NextSection(type, backwards)
    if a:backwards
        let dir = '?'
    else
        let dir = '/'
    endif

    execute 'silent normal! ' . dir . 'foo' . "\r"
endfunction</code></pre>


<p>Now the function uses the <code>execute normal!</code> pattern we've seen before to perform
either <code>/foo</code> or <code>?foo</code>, depending on the value given for <code>backwards</code>.  This is
a good start.</p>
<p>Moving on, we're obviously going to need to search for something other than
<code>foo</code>, and that pattern is going to depend on whether we want to use the first
or second definition of section headings.</p>
<p>Change <code>NextSection</code> to look like this:</p>
<pre class="codehilite"><code class="language-vim">function! s:NextSection(type, backwards)
    if a:type == 1
        let pattern = 'one'
    elseif a:type == 2
        let pattern = 'two'
    endif

    if a:backwards
        let dir = '?'
    else
        let dir = '/'
    endif

    execute 'silent normal! ' . dir . pattern . "\r"
endfunction</code></pre>


<p>Now we just need to fill in the patterns, so let's go ahead and do that.</p>
<h2 id="top-level-text-sections">Top Level Text Sections</h2>
<p>Replace the first <code>let pattern = '...'</code> line with the following:</p>
<pre class="codehilite"><code class="language-vim">let pattern = '\v(\n\n^\S|%^)'</code></pre>


<p>To understand how the regular expression works, remember the definition of
"section" that we're implementing:</p>
<blockquote>
<p>Any line following a blank line that contains a non-whitespace as the first
character, or the first line in the file.</p>
</blockquote>
<p>The <code>\v</code> at the beginning simply forces "very magic" mode like we've seen
several times before.</p>
<p>The remainder of the regex is a group with two options.  The first, <code>\n\n^\S</code>,
searches for "a newline, followed by a newline, followed by a non-whitespace
character".  This finds the first set of lines in our definition.</p>
<p>The other option is <code>%^</code>, which is a special Vim regex atom that means
"beginning of file".</p>
<p>Now we're at a point where we can try out the first two mappings.  Save
<code>ftplugin/potion/sections.vim</code> and run <code>:set filetype=potion</code> in your sample
Potion buffer.  The <code>[[</code> and <code>]]</code> commands should work, but somewhat oddly.</p>
<h2 id="search-flags">Search Flags</h2>
<p>You'll notice that when you move between sections your cursor gets placed on the
blank line above the one we actually want to move to.  Think about why this
happens before reading on.</p>
<p>The answer is that we searched using <code>/</code> (or <code>?</code>) and by default Vim places your
cursor at the beginning of matches.  For example, when you run <code>/foo</code> your
cursor will be placed on the <code>f</code> in <code>foo</code>.</p>
<p>To tell Vim to put the cursor at the end of the match instead of the beginning,
we can use a search flag.  Try searching in your Potion file like so:</p>
<pre class="codehilite"><code class="language-vim">/factorial/e</code></pre>


<p>Vim will find the word <code>factorial</code> and move you to it.  Press <code>n</code> a few times to
move through the matches.  The <code>e</code> flag tells Vim to put the cursor at the end
of matches instead of the beginning.  Try it in the other direction too:</p>
<pre class="codehilite"><code class="language-vim">?factorial?e</code></pre>


<p>Let's modify our function to use a search flag to put our cursor on the other
end of the matches for this section:</p>
<pre class="codehilite"><code class="language-vim">function! s:NextSection(type, backwards)
    if a:type == 1
        let pattern = '\v(\n\n^\S|%^)'
        let flags = 'e'
    elseif a:type == 2
        let pattern = 'two'
        let flags = ''
    endif

    if a:backwards
        let dir = '?'
    else
        let dir = '/'
    endif

    execute 'silent normal! ' . dir . pattern . dir . flags . "\r"
endfunction</code></pre>


<p>We've changed two things here.  First, we set a <code>flags</code> variable depending on
the type of section movement.  For now we only worry about the first type, which
is going to need a flag of <code>e</code>.</p>
<p>Second, we've concatenated <code>dir</code> and <code>flags</code> to the search string.  This will
add <code>?e</code> or <code>/e</code> depending on which direction we're searching.</p>
<p>Save the file, switch back to your sample Potion file and run <code>:set ft=potion</code>
to make the changes take effect.  Now try <code>[[</code> and <code>]]</code> to see them working
properly!</p>
<h2 id="function-definitions">Function Definitions</h2>
<p>It's time to tackle our second definition of "section", and luckily this one is
much more straightforward than the first.  Recall the definition we need to
implement:</p>
<blockquote>
<p>Any line that contains a non-whitespace as the first character, an equal sign
somewhere inside the line, and ends with a colon.</p>
</blockquote>
<p>We can use a fairly simple regex to find these lines.  Change the second <code>let
pattern = '...'</code> line in the function to this:</p>
<pre class="codehilite"><code class="language-vim">let pattern = '\v^\S.*\=.*:$'</code></pre>


<p>This regex should look much less frightening than the last one.  I'll leave it
as an exercise for you to figure out how it works -- it's a pretty
straightforward translation of our definition.</p>
<p>Save the file, run <code>:set filetype=potion</code> in <code>factorial.pn</code>, and try out the new
<code>][</code> and <code>[]</code> mappings.  They should work as expected.</p>
<p>We don't need a search flag here because putting the cursor at the beginning of
the match (the default) works just fine.</p>
<h2 id="visual-mode">Visual Mode</h2>
<p>Our section movement commands work great in normal mode, but we need to add
a bit more to make them work in visual mode as well.  First, change the function
to look like this:</p>
<pre class="codehilite"><code class="language-vim">function! s:NextSection(type, backwards, visual)
    if a:visual
        normal! gv
    endif

    if a:type == 1
        let pattern = '\v(\n\n^\S|%^)' 
        let flags = 'e'
    elseif a:type == 2
        let pattern = '\v^\S.*\=.*:$'
        let flags = ''
    endif

    if a:backwards
        let dir = '?'
    else
        let dir = '/'
    endif

    execute 'silent normal! ' . dir . pattern . dir . flags . "\r"
endfunction</code></pre>


<p>Two things have changed.  First, the function takes an extra argument so it knows
whether it's being called from visual mode or not.  Second, if it's called from
visual mode we run <code>gv</code> to restore the visual selection.</p>
<p>Why do we need to do this?  Let's try something that will make it clear.
Visually select some text in any buffer and then run the following command:</p>
<pre class="codehilite"><code class="language-vim">:echom "hello"</code></pre>


<p>Vim will display <code>hello</code> but the visual selection will also be cleared!</p>
<p>When running an ex mode command with <code>:</code> the visual selection is always cleared.
The <code>gv</code> command reselects the previous visual selection, so this will "undo"
the clearing.  It's a useful command, and can be handy in your day-to-day work
too.</p>
<p>Now we need to update the existing mappings to pass <code>0</code> in for the new <code>visual</code>
argument:</p>
<pre class="codehilite"><code class="language-vim">noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; ]]
        \ :call &lt;SID&gt;NextSection(1, 0, 0)&lt;cr&gt;

noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; [[
        \ :call &lt;SID&gt;NextSection(1, 1, 0)&lt;cr&gt;

noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; ][
        \ :call &lt;SID&gt;NextSection(2, 0, 0)&lt;cr&gt;

noremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; []
        \ :call &lt;SID&gt;NextSection(2, 1, 0)&lt;cr&gt;</code></pre>


<p>Nothing too complex there.  Now let's add the visual mode mappings as the final
piece of the puzzle:</p>
<pre class="codehilite"><code class="language-vim">vnoremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; ]]
        \ :&lt;c-u&gt;call &lt;SID&gt;NextSection(1, 0, 1)&lt;cr&gt;

vnoremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; [[
        \ :&lt;c-u&gt;call &lt;SID&gt;NextSection(1, 1, 1)&lt;cr&gt;

vnoremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; ][
        \ :&lt;c-u&gt;call &lt;SID&gt;NextSection(2, 0, 1)&lt;cr&gt;

vnoremap &lt;script&gt; &lt;buffer&gt; &lt;silent&gt; []
        \ :&lt;c-u&gt;call &lt;SID&gt;NextSection(2, 1, 1)&lt;cr&gt;</code></pre>


<p>These mappings all pass <code>1</code> for the <code>visual</code> argument to tell Vim to reselect
the last selection before performing the movement.  They also use the <code>&lt;c-u&gt;</code>
trick we learned about in the Grep Operator chapters.</p>
<p>Save the file, <code>:set ft=potion</code> in the Potion file and you're done!  Give your
new mappings a try.  Things like <code>v]]</code> and <code>d[]</code> should all work properly now.</p>
<h2 id="why-bother">Why Bother?</h2>
<p>This has been a long chapter for some seemingly small functionality, but you've
learned and practiced a lot of useful things along the way:</p>
<ul>
<li>Using <code>noremap</code> instead of <code>nnoremap</code> to create mappings that work as
  movements and motions.</li>
<li>Using a single function with several arguments to simplify creating related
  mappings.</li>
<li>Building up functionality in a Vimscript function incrementally.</li>
<li>Building up an <code>execute 'normal! ...'</code> string programmatically.</li>
<li>Using simple searches to move around with regexes.</li>
<li>Using special regex atoms like <code>%^</code> (beginning of file).</li>
<li>Using search flags to modify how searches work.</li>
<li>Handling visual mode mappings that need to retain the visual selection.</li>
</ul>
<p>Go ahead and do the exercises (it's just a bit of <code>:help</code> reading) and then grab
some ice cream.  You've earned it after this chapter!</p>
<h2 id="exercises">Exercises</h2>
<p>Read <code>:help search()</code>.  This is a useful function to know, but you can also use
the flags listed with the <code>/</code> and <code>?</code> commands.</p>
<p>Read <code>:help ordinary-atom</code> to learn about more interesting things you can use in
search patterns.</p></div>

        <div class="prevnext">
            
                <a class="prev" href="50.html">&laquo; Previous</a>
            
            
                <a class="next" href="52.html">Next &raquo;</a>
            
        </div>
    </section>


            <footer class="sixteen columns">
                Made by <a href="http://stevelosh.com">Steve Losh</a>.

                <a href="/license.html">License</a>.

                Built with
                <a href="http://bitbucket.org/sjl/bookmarkdown/">Bookmarkdown</a>.
            </footer>
        </div>

        
            <script type="text/javascript">
                var _gaq = _gaq || [];
                _gaq.push(['_setAccount', 'UA-15328874-8']);
                _gaq.push(['_trackPageview']);

                (function() {
                 var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
                 })();
            </script>
        

        
            <script type="text/javascript">
                var _gauges = _gauges || [];
                (function() {
                 var t   = document.createElement('script');
                 t.type  = 'text/javascript';
                 t.async = true;
                 t.id    = 'gauges-tracker';
                 t.setAttribute('data-site-id', '4e8f83b7f5a1f546e200000d');
                 t.src = '//secure.gaug.es/track.js';
                 var s = document.getElementsByTagName('script')[0];
                 s.parentNode.insertBefore(t, s);
                 })();
             </script>
        
    </body>
</html>
